package com.woniu108.extra.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu108.carService.commos.dto.AddressInfoDto;
import com.woniu108.carService.commos.dto.UserInfoDto;
import com.woniu108.carService.commos.exception.WoniuException;
import com.woniu108.carService.commos.model.Result;
import com.woniu108.carService.commos.util.JWTUtil;
import com.woniu108.carService.commos.util.RedisUtil;
import com.woniu108.carService.commos.util.StaticData;
import com.woniu108.extra.client.PersonClient;
import com.woniu108.extra.form.AddUserAddressInfoForm;
import com.woniu108.extra.form.ChangeUserAddressForm;
import com.woniu108.extra.model.AddressInfo;
import com.woniu108.extra.service.AddressInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址表 前端控制器
 * </p>
 *
 * @author yanxi
 * @since 2024-05-23
 */
@RestController
@RequestMapping("/addressInfo")
@Api(tags="地址信息接口")
public class AddressInfoController {


    @Resource
    private AddressInfoService addressInfoService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private PersonClient personClient;

    public String getUserId(String token) {
        String refreshToken = redisUtil.getString(token);
        String userId = JWTUtil.parseUserToken(refreshToken).get("userId").toString();
        return userId;
    }

    /**
     * ID查找用户收货地址信息
     * @param addressId 地址ID
     * @return AddressInfoDto  用户地址详细信息
     */
    @GetMapping("/getByAddressId/{addressId}.c")
    @ApiOperation("ID查找用户收货地址信息")
    @ApiImplicitParam(name = "addressId", value = "地址ID")
    public Result<AddressInfoDto> AddressInfoById(@PathVariable("addressId") Integer addressId) {
        AddressInfo addressInfo = addressInfoService.getById(addressId);
        if (ObjectUtil.isEmpty(addressInfo)) throw new WoniuException("地址信息不存在", 10001);
        return Result.getResult(AddressInfoDto.class).setData(BeanUtil.toBean(addressInfo, AddressInfoDto.class));
    }

    /**
     * 设置用户默认收货地址
     * @param token
     * @param addressId 地址ID
     * @return result 是否正常访问接口结果
     */
    @GetMapping("/setDefaultAddress")
    @ApiOperation("设置用户默认收货地址")
    @ApiImplicitParam(name = "addressId", value = "地址ID")
    public Result setDefaultAddress(@RequestHeader String token, Integer addressId) {
        String userId = this.getUserId(token);
        AddressInfo addressInfo = addressInfoService.getById(addressId);
        if (ObjectUtil.isEmpty(addressInfo)) throw new WoniuException("地址信息不存在", 10001);
        if (addressInfo.getUserId() != userId) throw new WoniuException("非本账号地址", 10001);
        if (addressInfo.getIsDefault() == StaticData.ADDRESS_DEFAULT)
            throw new WoniuException("已设置为默认地址,请勿重复操作", 10001);
        QueryWrapper<AddressInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<AddressInfo> list = addressInfoService.list(wrapper);
        for (AddressInfo info : list) {
            if (info.getIsDefault() == StaticData.ADDRESS_DEFAULT) {
                info.setIsDefault(StaticData.ADDRESS_NOT_DEFAULT);
                addressInfoService.updateById(info);
            }
        }
        addressInfo.setIsDefault(StaticData.ADDRESS_DEFAULT);
        addressInfoService.updateById(addressInfo);
        return Result.getResult().setMsg("设置默认地址成功");
    }

    /**
     * 删除用户收货地址信息
     * @param token
     * @param addressId 地址ID
     * @return result 是否正常访问接口结果
     */
    @GetMapping("/deleteUserAddress")
    @ApiOperation("删除用户收货地址信息")
    @ApiImplicitParam(name = "addressId", value = "地址ID")
    public Result deleteUserAddress(@RequestHeader String token, Integer addressId) {
        String userId = this.getUserId(token);
        AddressInfo addressInfo = addressInfoService.getById(addressId);
        if (ObjectUtil.isEmpty(addressInfo)) throw new WoniuException("地址信息不存在", 10001);
        if (addressInfo.getUserId() != userId) throw new WoniuException("非本账号地址", 10001);
        if (addressInfo.getIsDefault() == StaticData.ADDRESS_DEFAULT)
            throw new WoniuException("已设置为默认地址,请先设置其他默认地址再操作删除", 10001);
        addressInfoService.removeById(addressInfo);
        return Result.getResult().setMsg("删除地址信息成功");
    }

    /**
     * 新增用户收货地址信息
     * @param token
     * @param form  新增地址信息
     * @return result 是否正常访问接口结果
     */
    @PostMapping("/addUserAddressInfo")
    @ApiOperation("新增用户收货地址信息")
    public Result addUserAddressInfo(@RequestHeader String token, @RequestBody AddUserAddressInfoForm form) {
        String userId = this.getUserId(token);
        Result<UserInfoDto> result = personClient.getByUserId(userId);
        if (result.getCode() != 200) throw new WoniuException(result.getMsg(), result.getCode());
        if (ObjectUtil.isEmpty(result.getData())) throw new WoniuException("用户不存在", 10001);
        AddressInfo addressInfo = BeanUtil.toBean(form, AddressInfo.class);
        addressInfo.setUserId(userId);
        QueryWrapper<AddressInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<AddressInfo> list = addressInfoService.list(wrapper);
        //如果未录入过收货地址信息,则设置为默认，否则为非默认
        if (ObjectUtil.isEmpty(list)) {
            addressInfo.setIsDefault(StaticData.ADDRESS_DEFAULT);
        } else {
            addressInfo.setIsDefault(StaticData.ADDRESS_NOT_DEFAULT);
        }
        addressInfoService.save(addressInfo);
        return Result.getResult().setMsg("新增收货地址成功");
    }

    /**
     * 修改用户收货地址信息
     * @param token
     * @param form  修改地址信息
     * @return result 是否正常访问接口结果
     */
    @PostMapping("/changeUserAddressInfo")
    @ApiOperation("修改用户收货地址信息")
    public Result changeUserAddressInfo(@RequestHeader String token, @RequestBody ChangeUserAddressForm form) {
        String userId = this.getUserId(token);
        Result<UserInfoDto> result = personClient.getByUserId(userId);
        if (result.getCode() != 200) throw new WoniuException(result.getMsg(), result.getCode());
        if (ObjectUtil.isEmpty(result.getData())) throw new WoniuException("用户不存在", 10001);
        AddressInfo addressInfo = addressInfoService.getById(form.getAddressId());
        if (ObjectUtil.isEmpty(addressInfo)) throw new WoniuException("地址信息不存在", 10001);
        if (form.getAddressName() != null) addressInfo.setAddressName(form.getAddressName());
        if (form.getRecevierName() != null) addressInfo.setRecevierName(form.getRecevierName());
        if (form.getRecevierPhone() != null) addressInfo.setRecevierPhone(form.getRecevierPhone());
        addressInfoService.updateById(addressInfo);
        return Result.getResult().setMsg("修改收货地址信息成功");
    }

    /**
     * 列表展示用户收货地址信息
     * @param token
     * @return  List<AddressInfoDto> 用户所有的收货地址信息
     */
    @GetMapping("/userAddressList.api")
    @ApiOperation("列表展示用户收货地址信息")
    public Result<List<AddressInfoDto>> userAddressList(@RequestHeader String token){
        String userId = this.getUserId(token);
        QueryWrapper<AddressInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<AddressInfo> list = addressInfoService.list(wrapper);
        if(list.size()==0) throw new WoniuException("该用户暂无地址信息",10001);
        List<AddressInfoDto> dtos = new ArrayList<>();
        for (AddressInfo addressInfo : list) {
            AddressInfoDto dto = BeanUtil.toBean(addressInfo, AddressInfoDto.class);
            dtos.add(dto);
        }
        return Result.newListInstance(AddressInfoDto.class).setData(dtos);
    }
}

